<?php

namespace app\model;

use think\Model;

class Banner extends Model
{
    // 设置当前模型对应的数据表
    protected $name = 'banner';
    // 设置当前模型主键
    protected $pk = 'id';

    //类型
    const TYPE_JUMP = 'jump'; //跳转
    const TYPE_ACTIVITY = 'activity'; //活动
    const TYPE_ARR = [
        self::TYPE_JUMP => '跳转',
        self::TYPE_ACTIVITY => '活动',
    ];

    public function activity()
    {
        return $this->hasOne(Activity::class, 'id', 'activity_id');
    }

    // 获取视频推荐数据
    public function getList($fields = 'video_id', $order = 'sort desc')
    {
        $data = $this::field($fields)->order($order)->select();
        return $data ? $data->toArray() : [];
    }

    public function selectByAppletIdList(array $fields, int $appletId)
    {
        $data = $this::with(['activity' => function($query) use($appletId){
            $query->whereRaw('json_contains(applet_ids,json_array(?))', [$appletId])
            ->where('start_at','<=',date('Y-m-d H:i:s'))
            ->where('end_at','>',date('Y-m-d H:i:s'))
            ->withField(['id']);
        }])->field($fields)->order('sort desc')->select();
        return $data ? $data->toArray() : [];
    }

    /**
     * 新增/更新
     * 
     * @dateTime 2022/08/24
     * @param array $params
     * @return fixed
     */
    public function edit($params)
    {
        if (empty($params['id'])) {
            $data = $this::create($params);
            return $data->id;
        }
        $this::update($params);
        return $params['id'];
    }

    /**
     * 根据Id获取数据
     * 
     * @dateTime 2022/09/02
     * @author zhixiang0215@126.com
     * @param int id
     * @param string fields
     * @return array
     */
    public function getInfoById(int $id, string $fields = 'id')
    {
        $data = $this::where(['id' => $id])->field($fields)->find();
        return $data ? $data->toArray() : [];
    }

    /**
     * 根据获取数据
     * 
     * @dateTime 2022/09/24
     * @author zhixiang0215@126.com
     * @param array where
     * @param string fields
     * @param string order
     * @param int limit
     * @return array
     */
    public function getDataByWhere(array $where, string $fields = 'id', string $order = 'sort desc')
    {
        $model = $this::where($where)->field($fields)->order($order);

        $data = $model->select();
        return $data ? $data->toArray() : [];
    }
}
